<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\Course\CourseDao;
use App\Http\Traits\Errors;

class CourseService extends BaseService
{
    use Errors;

    protected $courseDao;

    public function __construct(CourseDao $courseDao)
    {
        $this->courseDao = $courseDao;
    }

    public function lists()
    {
        $keyword   = request('key_word') ?? '';
        $condition = [
            'status' => 1,
        ];

        if (!empty($keyword)) {
            $condition[] = ['name', 'like', '%' . $keyword . '%'];
        }
        $page   = request('page') ?? 1;
        $size   = request('size') ?? 10;
        $field  = ['id', 'name', 'category_id'];
        $offset = ($page * $size) - $size;
        return $this->courseDao->getModel()->where($condition)->with(["categoryInfo" => function ($query) {
            $query->select('id', 'name');
        }])->limit($size)->offset($offset)->orderBy('created_at', 'desc')->get($field);
    }

    public function detail()
    {
        $detailId = request('c_id') ?? 0;
        $detail   = $this->courseDao->getModel()->where(['id' => $detailId, 'valid' => 1])->with(["campusInfo" => function ($query) {
            $query->select(['id', 'name', 'contact', 'logo', 'longitude', 'latitude', 'address']);
        }, "courseSectionInfo"                                                                                 => function ($query) {
            $query->select(['id', 'course_id', 'name', 'serial_number', 'class_time', 'begin_time', 'end_time']);
        }, "teacherInfo"                                                                                       => function ($query) {
            $query->select(['id', 'name', 'avatar', 'intro', 'sex', 'age', 'edu_max', 'mobile']);
        }])->withCount('courseSectionInfo')->first();
        if (!$detail) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('课程不存在'));
        }
        $introLen = mb_strlen($detail['intro']);
//        $detail['long_intro'] = $detail['intro'] . '...收起';
        $detail['long_intro'] = $detail['intro'];
        $detail['str_length'] = $introLen;
        if ($introLen > 39) {
//            $detail['intro'] = mb_substr($detail['intro'], 0, 39) . '...展开';
            $detail['intro'] = mb_substr($detail['intro'], 0, 39);
        }

        return $detail;
    }

}
